package com.truckdispatching.upgrade;

import java.io.File;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.widget.ScrollView;
import android.widget.TextView;

import com.truckdispatching.activity.BaseActivity;
import com.truckdispatching.http.controller.CheckUpdateHttpController;
import com.truckdispatching.http.util.OnResponseHandler;
import com.truckdispatching.upgrade.ApkDownloadTask.ApkDownloadListener;

public class UpgradeManager {
	private static UpgradeManager instance;
	private String mCurrentVersion = null;
	private Context mContext;
	private ProgressDialog mDownloadProgressDialog;
	private ApkDownloadHandler mApkDownloadHandler;

	private boolean isForce = false;
	private String updateDownloadUrl = ""; // 版本更新的下载地址
	private String updateMessage = "发现最新版本";

	private CheckUpdateHttpController mCheckUpdateHttpController;

	private UpgradeManager() {

	}

	public synchronized static UpgradeManager getInstance() {
		if (instance == null) {
			instance = new UpgradeManager();
		}
		return instance;
	}

	/**
	 * 检查版本
	 */
	public void checkVersion(final boolean isAutoCheck, Context context) {
		this.mContext = context;
		if (mCurrentVersion == null) {
			PackageManager packageManager = mContext.getPackageManager();
			PackageInfo packInfo;
			try {
				packInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
				mCurrentVersion = packInfo.versionName;
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		}
		if (!isAutoCheck) {
			showLoadingDialog();
		}
		if (mCheckUpdateHttpController != null) {
			mCheckUpdateHttpController.cancelHttpRequest();
		}
		mCheckUpdateHttpController = new CheckUpdateHttpController();
		mCheckUpdateHttpController.setOnResponseListener(new OnResponseHandler() {

			@Override
			public void onResponseError(int errorCode, String errorMessage) {
				if (!isAutoCheck) {
					dismissLoadingDialog();
					((BaseActivity)mContext).showToast("网络请求失败");
				}
			}

			@Override
			public void onResponse(Object response) {
				if (!isAutoCheck) {
					dismissLoadingDialog();
				}
				HashMap<String, Object> map = (HashMap<String, Object>) response;
				if (map != null) {
					String version = (String) map.get("version");
					if (!version.equals(mCurrentVersion)) {
						isForce = (Boolean) map.get("force");
						updateDownloadUrl = (String) map.get("url");
						updateMessage = "检查到新版本  " + version;
						if (isForce) {
							showForceUpgradeDialog();
						} else {
							showNormalUpgradeDialog();
						}
					} else {
						if (!isAutoCheck) {
							new AlertDialog.Builder(mContext).setTitle("提示").setMessage("当前已经是最新版本，无需更新")
									.setPositiveButton("确定", null).show();
						}
					}
				} else {
					if (!isAutoCheck) {
						new AlertDialog.Builder(mContext).setTitle("提示").setMessage("当前已经是最新版本，无需更新")
								.setPositiveButton("确定", null).show();
					}
				}
			}
		});
		mCheckUpdateHttpController.sendRequest(mCurrentVersion);
	}

	private ProgressDialog mProgressDialog;

	protected void showLoadingDialog() {
		if (mProgressDialog == null) {
			mProgressDialog = new ProgressDialog(mContext);
			mProgressDialog.setMessage("加载中。。。");
			mProgressDialog.setCanceledOnTouchOutside(false);
			mProgressDialog.setCancelable(false);
		}
		mProgressDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
	}

	private void showForceUpgradeDialog() {
		ScrollView sv = new ScrollView(mContext);
		TextView tv = new TextView(mContext);
		tv.setText(updateMessage);
		sv.addView(tv);
		AlertDialog updateDialog = new AlertDialog.Builder(mContext).setTitle("版本更新").setView(sv).setPositiveButton(
				"立即升级", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (updateDownloadUrl.toLowerCase().endsWith(".apk")) {
							mDownloadProgressDialog = createDownloadProgressDialog();
							mDownloadProgressDialog.show();
							mApkDownloadHandler = new ApkDownloadHandler();
							startDownloadApkFileTask(updateDownloadUrl, mApkDownloadHandler);
						} else {
							Intent intent = new Intent();
							intent.setAction("android.intent.action.VIEW");
							Uri uri = Uri.parse(updateDownloadUrl);
							intent.setData(uri);
							mContext.startActivity(intent);
							exitApplication();
						}
					}
				}).setNegativeButton("退出", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				exitApplication();
			}
		}).create();
		updateDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				exitApplication();
			}
		});
		updateDialog.setCanceledOnTouchOutside(false);
		updateDialog.show();
	}

	private void showNormalUpgradeDialog() {
		ScrollView sv = new ScrollView(mContext);
		TextView tv = new TextView(mContext);
		tv.setText(updateMessage);
		sv.addView(tv);
		AlertDialog updateDialog = new AlertDialog.Builder(mContext).setTitle("版本更新").setView(sv).setPositiveButton(
				"升级", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (updateDownloadUrl.toLowerCase().endsWith(".apk")) {
							mDownloadProgressDialog = createDownloadProgressDialog();
							mDownloadProgressDialog.show();
							mApkDownloadHandler = new ApkDownloadHandler();
							startDownloadApkFileTask(updateDownloadUrl, mApkDownloadHandler);
						} else {
							Intent intent = new Intent();
							intent.setAction("android.intent.action.VIEW");
							Uri uri = Uri.parse(updateDownloadUrl);
							intent.setData(uri);
							mContext.startActivity(intent);
							exitApplication();
						}
					}
				}).setNegativeButton("取消", null).create();
		updateDialog.setCanceledOnTouchOutside(false);
		updateDialog.show();
	}

	/**
	 * 开始下载新版本的安装文件
	 * 
	 * @param downloadUrl
	 * @param handler
	 */
	private void startDownloadApkFileTask(String downloadUrl, final ApkDownloadHandler handler) {
		new Thread(new ApkDownloadTask(downloadUrl, new ApkDownloadListener() {

			@Override
			public void downloadComplete(File apkFile) {
				installApk(apkFile);
				exitApplication();
			}

			@Override
			public void downloadProgress(int downloadSize, int totalSize) {
				handler.obtainMessage(ApkDownloadHandler.MSG_DOWNLOAD_PROGRESS, downloadSize, totalSize).sendToTarget();
			}

			@Override
			public void downloadFail() {
				handler.obtainMessage(ApkDownloadHandler.MSG_DOWNLOAD_FAILED).sendToTarget();
			}

		})).start();
	}

	/**
	 * 创建下载进度显示的对话框
	 * 
	 * @return
	 */
	private ProgressDialog createDownloadProgressDialog() {
		ProgressDialog downloadDialog = new ProgressDialog(mContext);
		downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		downloadDialog.setIndeterminate(false);
		downloadDialog.setMessage("下载中···");
		downloadDialog.setCancelable(true);
		downloadDialog.setCanceledOnTouchOutside(false);
		downloadDialog.setProgress(0);
		downloadDialog.setMax(100);
		downloadDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				exitApplication();
			}
		});
		return downloadDialog;
	}

	/**
	 * 退出应用
	 */
	private void exitApplication() {
		((Activity) mContext).getApplication().onTerminate();
	}

	/**
	 * 安装apk文件
	 * 
	 * @param filename文件的路径
	 */
	private void installApk(File file) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		String type = "application/vnd.android.package-archive";
		intent.setDataAndType(Uri.fromFile(file), type);
		mContext.startActivity(intent);
	}

	private class ApkDownloadHandler extends Handler {
		public static final int MSG_DOWNLOAD_PROGRESS = 2;
		public static final int MSG_DOWNLOAD_FAILED = 3;

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_DOWNLOAD_PROGRESS:
				mDownloadProgressDialog.setProgress(msg.arg1 * 100 / msg.arg2);
				break;
			case MSG_DOWNLOAD_FAILED:
				showDownloadFailedDialog();
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 显示下载失败对话框
	 */
	private void showDownloadFailedDialog() {
		AlertDialog downloadFailedDialog = new AlertDialog.Builder(mContext).setTitle("下载失败").setMessage(
				"安装文件下载失败，是否重试？").setPositiveButton("重试", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				mDownloadProgressDialog.setProgress(0);
				mDownloadProgressDialog.show();
				startDownloadApkFileTask(updateDownloadUrl, mApkDownloadHandler);
			}
		}).setNegativeButton("退出", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				exitApplication();
			}
		}).create();
		downloadFailedDialog.setCanceledOnTouchOutside(false);
		downloadFailedDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				exitApplication();
			}
		});
		downloadFailedDialog.show();
	}
}
